package com.ruoyi.camp.service.impl;

import com.ruoyi.camp.config.CampCore;
import com.ruoyi.camp.domain.CampLoginUser;
import com.ruoyi.camp.domain.CampUser;
import com.ruoyi.camp.service.ICampLoginService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.uuid.IdUtils;

/**
 * 微信登录服务实现
 *
 * @auth zhaoly
 * @date 2024-01-25 10:24
 */
@Service
public class CampLoginService implements ICampLoginService {

    @Value("${wechart.userType}")
    private String userType;
    @Value("${wechart.wxUser}")
    private String wxUser;


    @Value("${wechart.wxUserRole}")
    private String wxUserRole;

    @Autowired
    private CampCore core;

    @Autowired
    private TokenService tokenService;


    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private CampUserServiceImpl campUserService;

    @Autowired
    private ISysUserService userService;

    /**
     * 微信登录
     *
     * @param code     小程序预登录coce
     * @param userName 学号/工号/手机号
     * @param password 登录密码
     * @return 登录用户
     */
    @Override
    public CampLoginUser login(String code, String userName, String password) {

        // 请求wx后台通过code请求openid
        String openid = core.getOpenId(code);

        // String openid = code;

        // 获取不到openid直接返回
        if (StringUtils.isBlank(openid)) {
            return new CampLoginUser(userName, "", -1, "获取openid失败");
        }
        // 通过openid查询系统用户
        CampUser campUser = campUserService.selectCampUserByOpenId(openid);
        if (campUser == null) {
            register(openid);
        }
        campUser = campUserService.selectCampUserByOpenId(openid);
        if (campUser != null) {
            SysUser sysUser = userService.selectUserById(Long.valueOf(wxUser));
            sysUser.setUserName(campUser.getUsername());
            sysUser.setNickName((campUser.getUserid()));
            sysUser.setRoleId(Long.valueOf(wxUserRole));
            sysUser.setEmail((campUser.getOpenid()));
            sysUser.setPhonenumber(campUser.getPhone());
            sysUser.setPassword(campUser.getPassword());

            CampLoginUser wxLoginUser = generatorLoginUser(sysUser);
            wxLoginUser.setUserId((campUser.getUserid()));
            wxLoginUser.setOpenId((campUser.getOpenid()));
            wxLoginUser.setImageUrl(campUser.getImageurl());

            wxLoginUser.setPhone(campUser.getPhone());
            wxLoginUser.setUsername(campUser.getUsername());
            return wxLoginUser;
        }

        // 通过用户名密码查询系统用户
        // sysUser = campUserService.selectCampUserByUserName(userName);

        return new CampLoginUser(userName, "", -1, "用户名或密码不正确");
    }

    /**
     * 生成微信用户登录参数
     *
     * @param user 系统用户
     * @return
     */
    private CampLoginUser generatorLoginUser(SysUser user) {

//        LoginUser loginUser = new LoginUser();]
//        loginUser.setUser(sysUser);
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));

        String token = tokenService.createToken(loginUser);
        return new CampLoginUser(user.getUserName(), user.getUserName(), token);
    }


    /**
     * 新用户注册
     *
     * @param user 新注册用户实例
     * @return 注册结果
     */
    @Override
    public int updateUserInfo(CampUser user) {

        CampUser sysUser = campUserService.selectCampUserByUserid(user.getUserid());
        if (sysUser == null) {
            return -2;
        }
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        return campUserService.updateCampUser(user);
    }

    @Override
    public int register(String openid) {
        // 获取不到openid直接返回
        if (StringUtils.isBlank(openid)) {
            return -1;
        }

        CampUser user = new CampUser();
        user.setOpenid(openid);
        // 通过openid查询系统用户
        CampUser sysUser = campUserService.selectCampUserByOpenId(openid);
        if (sysUser != null) {
            return -2;
        }
        user.setUserid(IdUtils.randomUUID());
        user.setImageurl("https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0");
        user.setUsername("用户" + UUID.randomUUID().toString().split("-")[0]);
        if (StringUtils.isNotEmpty(user.getPassword())) {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        }
        return campUserService.insertCampUser(user);
    }


}
